package net.guerlab.smart.wx.api.autoconfig;

import lombok.AllArgsConstructor;
import net.guerlab.smart.platform.commons.util.BeanConvertUtils;
import net.guerlab.smart.wx.api.WxAppApi;
import net.guerlab.smart.wx.core.domain.WxAppDTO;
import net.guerlab.smart.wx.core.exception.WxAppInvalidException;
import net.guerlab.smart.wx.core.searchparams.WxAppSearchParams;
import net.guerlab.smart.wx.service.service.WxAppService;
import net.guerlab.web.result.ListObject;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.*;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.lang.NonNull;

import java.util.List;

/**
 * @author guer
 */
@Configuration
@Conditional(WxAppApiLocalServiceAutoConfigure.WrapperCondition.class)
public class WxAppApiLocalServiceAutoConfigure {

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Bean
    @ConditionalOnBean(WxAppService.class)
    public WxAppApi wxAppApiLocalServiceWrapper(WxAppService service) {
        return new WxAppApiLocalServiceWrapper(service);
    }

    @SuppressWarnings("WeakerAccess")
    static class WrapperCondition implements Condition {

        @Override
        public boolean matches(@NonNull ConditionContext context, @NonNull AnnotatedTypeMetadata metadata) {
            try {
                return WrapperCondition.class.getClassLoader()
                        .loadClass("net.guerlab.smart.wx.service.service.WxAppService") != null;
            } catch (Exception e) {
                return false;
            }
        }
    }

    @AllArgsConstructor
    private static class WxAppApiLocalServiceWrapper implements WxAppApi {

        private WxAppService service;

        @Override
        public WxAppDTO findOne(String appId) {
            return service.selectByIdOptional(appId).orElseThrow(WxAppInvalidException::new).toDTO();
        }

        @Override
        public ListObject<WxAppDTO> findList(WxAppSearchParams searchParams) {
            return BeanConvertUtils.toListObject(service.selectPage(searchParams));
        }

        @Override
        public List<WxAppDTO> findAll(WxAppSearchParams searchParams) {
            return BeanConvertUtils.toList(service.selectAll(searchParams));
        }
    }

}
